package com.zenithmind.mall.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.zenithmind.mall.pojo.entity.ProductStock;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Update;

/**
 * 商品库存Mapper接口
 * 
 * @author ZenithMind Team
 * @since 2025-07-03
 */
@Mapper
public interface ProductStockMapper extends BaseMapper<ProductStock> {

    /**
     * 乐观锁更新库存
     * 
     * @param productId 商品ID
     * @param quantity 扣减数量
     * @param version 版本号
     * @return 更新行数
     */
    @Update("UPDATE mall_product_stock SET stock = stock - #{quantity}, " +
            "locked_stock = locked_stock + #{quantity}, version = version + 1, " +
            "update_time = NOW() WHERE product_id = #{productId} AND version = #{version} " +
            "AND stock >= #{quantity}")
    int decreaseStockWithLock(@Param("productId") String productId, 
                             @Param("quantity") Integer quantity, 
                             @Param("version") Integer version);

    /**
     * 释放锁定库存
     * 
     * @param productId 商品ID
     * @param quantity 释放数量
     * @return 更新行数
     */
    @Update("UPDATE mall_product_stock SET locked_stock = locked_stock - #{quantity}, " +
            "update_time = NOW() WHERE product_id = #{productId} AND locked_stock >= #{quantity}")
    int releaseLockedStock(@Param("productId") String productId, 
                          @Param("quantity") Integer quantity);

    /**
     * 确认扣减库存（将锁定库存转为实际扣减）
     * 
     * @param productId 商品ID
     * @param quantity 确认扣减数量
     * @return 更新行数
     */
    @Update("UPDATE mall_product_stock SET locked_stock = locked_stock - #{quantity}, " +
            "update_time = NOW() WHERE product_id = #{productId} AND locked_stock >= #{quantity}")
    int confirmDecreaseStock(@Param("productId") String productId, 
                            @Param("quantity") Integer quantity);
}
